package com.ljkj.cordial.chat.presenter;

import android.content.Context;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.adapter.ChatAdapter;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.ChatTableUnit;
import com.ljkj.cordial.chat.bean.PayLoad;
import com.ljkj.cordial.chat.dao.AlbumTableBean;
import com.ljkj.cordial.chat.dao.ChatTableBean;
import com.ljkj.cordial.chat.util.AlbumManageUtil;
import com.nic.view.widget.CircleImageView;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 照片
 */
public class PicturePresenter extends AChatPresenter {

    public PicturePresenter(int direction) {
        super(direction);
    }

    @Override
    public RecyclerView.ViewHolder getViewHolder(View view) {
        if (getDirection() == AChatPresenter.LEFT) {
            return new ViewLeftHolder(view);
        }
        return new ViewRightHolder(view);
    }

    @Override
    public void bindViewHolder(RecyclerView.ViewHolder holder, Object obj, int position) {
        ChatTableUnit item = (ChatTableUnit) obj;
        Context context = holder.itemView.getContext();
        if (getDirection() == LEFT) {
            ViewLeftHolder viewLeftHolder = (ViewLeftHolder) holder;
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewLeftHolder.cardView.getLayoutParams();
            if (getChatType() == Canstants.SINGLE_CHAT) {
                viewLeftHolder.tvTitle.setVisibility(View.GONE);
                params.topMargin = context.getResources().getDimensionPixelOffset(R.dimen.dimen_8);
                viewLeftHolder.cardView.setLayoutParams(params);
            } else {
                viewLeftHolder.tvTitle.setText(TextUtils.isEmpty(item.getAlias()) ? item.getTargetName() : item.getAlias());
            }

            setVisible(viewLeftHolder.cb, item.isVisible());
            setCheck(viewLeftHolder.cb, item.isChecked());
            viewLeftHolder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    item.setChecked(isChecked);
                    if (getOnCListener() != null) {
                        getOnCListener().onItemCheckChange(buttonView, item, position, isChecked);
                    }
                }
            });
            viewLeftHolder.ivMsg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    showLargePhoto(viewLeftHolder.chatItemProgress, v, item);
                }
            });
            viewLeftHolder.ivMsg.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (getOnCListener() != null) {
                        getOnCListener().onItemLongClick(v, item, position);
                        return true;
                    }
                    return false;
                }
            });
            viewLeftHolder.ivIsVisitor.setVisibility(IMSContacts.UserType.TOURISTS_USER.equals(item.getTargetType()) ? View.VISIBLE : View.GONE);
            if (isLoadAccess()) {
                showThumbPicture(item, viewLeftHolder.ivMsg, position);
            } else {
                showThumbPictureDef(item, viewLeftHolder.ivMsg);
            }
            loadAvatar(item, viewLeftHolder.ivAvatar);
            setReadFinishState(viewLeftHolder.tvDownTime, item.isStartReadFinish());
        } else {
            ViewRightHolder viewRightHolder = (ViewRightHolder) holder;
            setVisible(viewRightHolder.cb, item.isVisible());
            setCheck(viewRightHolder.cb, item.isChecked());
            if (item.isVisible()) {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewRightHolder.ivAvatar.getLayoutParams();
                params.addRule(RelativeLayout.LEFT_OF, viewRightHolder.cb.getId());
                params.rightMargin = viewRightHolder.cb.getContext().getResources().getDimensionPixelOffset(R.dimen.dimen_48);
            } else {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewRightHolder.ivAvatar.getLayoutParams();
                params.rightMargin = viewRightHolder.cb.getContext().getResources().getDimensionPixelOffset(R.dimen.dimen_16);
            }
            viewRightHolder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    item.setChecked(isChecked);
                    if (getOnCListener() != null) {
                        getOnCListener().onItemCheckChange(buttonView, item, position, isChecked);
                    }
                }
            });
            viewRightHolder.ivMsg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showLargePhoto(viewRightHolder.chatItemProgress, v, item);
                }
            });
            viewRightHolder.ivChatItemFail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (getOnCListener() != null) {
                        getOnCListener().onItemReloadClick(v, item, position);
                    }
                }
            });
            viewRightHolder.ivMsg.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (getOnCListener() != null) {
                        getOnCListener().onItemLongClick(v, item, position);
                        return true;
                    }
                    return false;
                }
            });
            refreshSendState(item, viewRightHolder.chatItemProgress, viewRightHolder.ivChatItemFail, viewRightHolder.tvDownTime);
            if (isLoadAccess()) {
                showThumbPicture(item, viewRightHolder.ivMsg, position);
            } else {
                showThumbPictureDef(item, viewRightHolder.ivMsg);
            }
            loadAvatar(item, viewRightHolder.ivAvatar);
        }
    }

    @Override
    public void bindViewHolder(ChatAdapter chatAdapter, int position, RecyclerView.ViewHolder holder, Object obj, PayLoad payLoad) {
        super.bindViewHolder(chatAdapter, position, holder, obj, payLoad);
        ChatTableUnit item = (ChatTableUnit) obj;
        if (getDirection() == LEFT) {
            ViewLeftHolder viewLeftHolder = (ViewLeftHolder) holder;
            for (int type : payLoad.getType()) {
                if (PayLoad.AVATAR == type) {
                    loadAvatar(item, viewLeftHolder.ivAvatar);
                }
                if (PayLoad.FILE == type) {
                    if (isLoadAccess()) {
                        showThumbPicture(item, viewLeftHolder.ivMsg, position);
                    } else {
                        showThumbPictureDef(item, viewLeftHolder.ivMsg);
                    }

                }
                if (PayLoad.DOWN_TIME == type) {
                    if (item.isStartReadFinish()) {
                        viewLeftHolder.tvDownTime.setText(item.getReadFinishFormatTime());
                    }
                }

            }

        } else {
            ViewRightHolder viewRightHolder = (ViewRightHolder) holder;
            for (int type : payLoad.getType()) {
                if (PayLoad.AVATAR == type)
                    loadAvatar(item, viewRightHolder.ivAvatar);
                if (PayLoad.FILE == type) {
                    if (isLoadAccess()) {
                        showThumbPicture(item, viewRightHolder.ivMsg, position);
                    } else {
                        showThumbPictureDef(item, viewRightHolder.ivMsg);
                    }

                }
                if (PayLoad.DOWN_TIME == type && item.getSendState() == ChatTableUnit.SEND_SUCCESS) {
                    if (item.isStartReadFinish()) {
                        viewRightHolder.tvDownTime.setText(item.getReadFinishFormatTime());
                    }
                }
                if (PayLoad.REQ_STATE == type) {
                    refreshSendState(item, viewRightHolder.chatItemProgress, viewRightHolder.ivChatItemFail, viewRightHolder.tvDownTime);
                }
            }
        }
    }

    private void showLargePhoto(ContentLoadingProgressBar loadingProgressBar, View v, ChatTableUnit item) {
//        if (!TextUtils.isEmpty(item.getAlbumId()) && Long.parseLong(item.getAlbumId()) > 0) {
//            AlbumTableBean al = AlbumTableBean.queryById(Long.parseLong(item.getAlbumId()));
//            if (al != null && !TextUtils.isEmpty(al.getMPath())) {
//                AlbumManageUtil
//                        .getInstance().lookLargePhoto(v.getContext(), al.getMPath());
//            } else {
//                requestLoad(loadingProgressBar, v, item);
//            }
//        } else {
//            requestLoad(loadingProgressBar, v, item);
//        }
        AlbumManageUtil.getInstance().stopVoice();
        if (onPictureListener != null) {
            onPictureListener.onItemClick(String.valueOf(item.getId()));
        }
//        MulPhotoPreviewActivity.jumpTo(v.getContext(), TextUtils.isEmpty(item.getGroupId()) ? item.getChatName() : item.getGroupId(), String.valueOf(item.getId()));
    }

    private void requestLoad(ContentLoadingProgressBar loadingProgressBar, View v, ChatTableUnit item) {
        if (loadingProgressBar.isShown()) {
            return;
        }
        loadingProgressBar.show();
        if (Canstants.SINGLE_CHAT == item.getFromType())
            AlbumManageUtil.getInstance().downLoadFileFriend(item.getFileUrl(), AlbumTableBean.TYPE_IMAGE, item.getTargetId(), new AlbumManageUtil.OnFileResponse() {
                @Override
                public void onResult(String url, String fileId) {
                    resultFile(fileId, loadingProgressBar, item, v);
                }
            });
        else
            AlbumManageUtil.getInstance().downLoadFileGroupMember(item.getFileUrl(), AlbumTableBean.TYPE_IMAGE
                    , item.getGroupType(), item.getGroupId(), item.getTargetType(), item.getTargetId(), new AlbumManageUtil.OnFileResponse() {
                        @Override
                        public void onResult(String url, String fileId) {
                            resultFile(fileId, loadingProgressBar, item, v);
                        }
                    });
    }

    private void resultFile(String fileId, ContentLoadingProgressBar loadingProgressBar, ChatTableUnit item, View v) {
        loadingProgressBar.hide();
        if (!TextUtils.isEmpty(fileId) && Long.parseLong(fileId) > 0) {
            item.setAlbumId(fileId);
            ChatTableBean.update(ChatTableUnit.getTable(item));
            AlbumTableBean al = AlbumTableBean.queryById(Long.parseLong(fileId));
            if (al != null && !TextUtils.isEmpty(al.getMPath())) {
                AlbumManageUtil
                        .getInstance().lookLargePhoto(v.getContext(), al.getMPath());
            }
        }
    }

    static class ViewLeftHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.cb)
        CheckBox cb;
        @BindView(R.id.iv_avatar)
        CircleImageView ivAvatar;
        @BindView(R.id.iv_is_visitor)
        ImageView ivIsVisitor;
        @BindView(R.id.ll_avatar)
        FrameLayout llAvatar;
        @BindView(R.id.tv_title)
        TextView tvTitle;
        @BindView(R.id.cv_picture)
        CardView cardView;
        @BindView(R.id.tv_downTime)
        TextView tvDownTime;
        @BindView(R.id.iv_msg)
        ImageView ivMsg;
        @BindView(R.id.chat_item_progress)
        ContentLoadingProgressBar chatItemProgress;

        ViewLeftHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            AChatPresenter.setProgressColor(chatItemProgress);
//            setIsRecyclable(false);
        }
    }

    static class ViewRightHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.cb)
        CheckBox cb;
        @BindView(R.id.iv_avatar)
        CircleImageView ivAvatar;
        @BindView(R.id.cv_picture)
        CardView cardView;
        @BindView(R.id.tv_downTime)
        TextView tvDownTime;
        @BindView(R.id.iv_msg)
        ImageView ivMsg;
        @BindView(R.id.chat_item_fail)
        ImageView ivChatItemFail;
        @BindView(R.id.chat_item_progress)
        ContentLoadingProgressBar chatItemProgress;

        ViewRightHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            AChatPresenter.setProgressColor(chatItemProgress);
//            setIsRecyclable(false);
        }
    }

    private OnPictureListener onPictureListener;

    public void setOnPictureListener(OnPictureListener onPictureListener) {
        this.onPictureListener = onPictureListener;
    }

    public interface OnPictureListener {
        void onItemClick(String chatId);
    }

}
